<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class MallRecommendGoods extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.mall_recommend_goods';
    protected $cacheModel = 'goods.mall_goods_recommend';

    /**
     * 获取指定推荐的商品
     * @param int $type 商品推荐类型
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getGoodsTypeRecommend($type)
    {
        $recommendGoodsInfo = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $type)->getDataAndSet(function () use ($type)
        {
            try
            {
                $data = $this->where(['status' => 1, 'type' => $type])->field('title,url,gids')->findOrFail()->toArray();
            }
            catch (\Exception $e)
            {
                $data = [];
            }
            return $data;
        });

        $data = [
            'title' => '',
            'banner_data' => null,
            'good_list' => null
        ];
        if ($recommendGoodsInfo)
        {
            $gids = explode(',', ($recommendGoodsInfo['gids'] ?? ''));

            $goodsInfo = (new MallGoods())->batGetInfo($gids, ['id', 'imgs', 'name', 'now_price', 'vip_price']);

            $data['title'] = $recommendGoodsInfo['title'];
            $data['banner_data'] = [
                'img' => $recommendGoodsInfo['url'],
                'target' => 'local',
                'link' => 'mall_store_goods_list?need_auth=0'
            ];

            $goodData = [];
            foreach ($goodsInfo as $k => $good)
            {
                $img = $good['imgs'] ? explode(',', $good['imgs'])[0] : '';

                if ($good['vip_price'] > 0)
                {   // 设置了会员价显示
                    $vipPrice = $good['vip_price']??'';
                } else
                {   // 没有设置会员价显示
                    $vipPrice = '';
                }
                // 组合商品数据
                $goodData[] = [
                    'gid' => $good['id'],
                    'img' => $img ? $img . '?x-oss-process=style/scale0.2' : '',
                    'title' => $good['name'],
                    'vip_desc' => '行星会员价',
                    'vip_price' => $vipPrice,
                    'price' => $good['now_price'],
                ];
            }

            $data['good_list'] = $goodData;
        }

        return $data;
    }
}
